<?php

//冲冲栽了十畦葱， 松松栽了十棵松。 冲冲说栽松不如栽葱， 松松说栽葱不如栽松。 是栽松不如栽葱， 还是栽葱不如栽松？

class Controller
{
    private $tags;
    private $users;
    private $statuss;

    function __construct() {
        $this->statuss = I\App::singleton()->getconfig('worktime', 'status');

        $this->users = I\DB::keyBy("select id, name, feishu from users");
        $this->tags = I\DB::keyBy("select id, name from tags");
    }

    public function start()
    {
        
        $now = time();
        $sql = "select * from tasks where status < 20 and deadline > 0 and deadline < $now and tag <> 16 order by tag, department, leader";
        $this->select($sql, '葱爆啦！！！葱爆啦！！！葱爆啦！！！');
    }

    public function todaylist() {
        $donotcheckday = getgpc('donotcheckday', false);
        if (!$donotcheckday) {
            $week = date('w');
            if ($week == 0 || $week == 6) {
                return;
            }
        }

        $sql = "select * from tasks where status < 30 order by tag, leader, status";
            
        $rows = I\DB::write()->query($sql);

        if (!$rows) {
            return;
        }

        $user_task = array();
        foreach ($rows as $task) {
            if (!isset($user_task[$task->leader])) {
                $user_task[$task->leader] = [];
            }
            $user_task[$task->leader][] = $task;
        }

        foreach ($user_task as $leader_id => $tasks) {
            $this->send_leader_task($leader_id, $tasks);
            sleep(2);
        }
    }

    private function send_leader_task($leader_id, $tasks) {
        $leader = $this->users[$leader_id];
        $at = "<at email=\"{$leader->feishu}\"></at> ";

        $content = "# {$at} 任务清单\n\n";

        foreach ($tasks as $task) {
            $tag = $this->tags[$task->tag];
            $status = $this->statuss[$task->status];
            $content .= "## [#{$task->id} &{$tag->name}&{$task->title}](http://10.77.34.52/task/show/{$task->id}) 状态 - {$status}\n\n";
        }

        $url = 'https://docs.oa.wanmei.net/woa/api/v1/webhook/send?key=1893f3d86f044e2141a4dd80cb2f68d3';
        M\Middle_Feishu::singleton()->send($content, $url);
    }

    public function todaytest() {
        $donotcheckday = getgpc('donotcheckday', false);
        if (!$donotcheckday) {
            $week = date('w');
            if ($week == 0 || $week == 6) {
                return;
            }
        }

        $db = I\DB::write();
        $sqlcount = "select count(*) as num from tasks where status = 50";
            
        $count_row = $db->row($sqlcount);
        $totalnum  = $count_row->num;

        if ($totalnum == 0) {
            return;
        }


        $at = '<at email="wangchaoran@pwrd.com"></at> <at email="1165079458@qq.com"></at> ';
        $content = "# {$at} 当前有 {$totalnum} 条可测试任务\n\n";

        $url = 'https://docs.oa.wanmei.net/woa/api/v1/webhook/send?key=1893f3d86f044e2141a4dd80cb2f68d3';
        M\Middle_Feishu::singleton()->send($content, $url);
    }
}
